<template>
  <div class="room">
    <!-- 房间页 -->
    <div class="page-room" v-if="true">
      <div class="head flex">
        <div class="h-l">
          <!-- <img v-if="roomData.user&&roomData.user.basicInfo!=undefined" :src="roomData.user.basicInfo.avatarUrl" alt=""> -->
          <div class="h-l-tag">发起者</div>
          <user-head :isTransition="false" :show="showHead" :user="userInfo"></user-head>
        </div>
        <div class="h-c flex">
          <!-- <div class="h-c-type">{{roomTypeText}}</div> -->
          <img src="/static/icon/timer.jpg" alt="">
          <div class="h-c-time">{{formateTime}}</div>
        </div>
        <div class="h-r">
          <div class="h-r-tag">挑战者</div>
          <user-head :isTransition="false" :show="showHead" :user="withUserInfo" :reverse="true"></user-head>
        </div>
      </div>

      <div class="content">
        <div class="c-top">
          <div class="c-type">{{roomTypeText}}</div>
        </div>
        <div class="c-bottom">
          <div class="c-btn flex">
            <button plain="true" class="btn-leave btnActive" @click="leaveRoom">
              <img src="/static/icon/leave.jpg" alt="">
              <div>离开</div>
            </button>
            <button plain="true" class="btn-invate" :class="{btnActive:roomStatus==0}" open-type="share">
              <img v-if="roomStatus==0" src="/static/icon/invate-active.jpg" alt="">
              <img v-else src="/static/icon/invate.jpg" alt="">
              <div>邀请</div>
            </button>
            <button plain="true" v-if="identity==2&&!hasWithUser" class="btn-join":class="{btnActive:roomStatus==0}" @click="cToJoin">
              <img v-if="roomStatus==0" src="/static/icon/join-active.jpg" alt="">
              <img v-else src="/static/icon/join.jpg" alt="">
              <div>参赛</div>
            </button>
            <button plain="true" v-if="identity==1" class="btn-watch":class="{btnActive:roomStatus==0}" @click="cToLook">
              <img v-if="roomStatus==0" src="/static/icon/watch-active.jpg" alt="">
              <img v-else src="/static/icon/watch.jpg" alt="">
              <div>围观</div>
            </button>
          </div>
          <div class="c-look-num">围观群众{{lookUserList.length}}人</div>
          <div class="foot">
            <div class="f-btn">
              <div v-if="identity==0&&roomStatus==0" class="btn-start" @click="startGame">开始</div>
              <div v-if="identity==2||roomStatus==1" class="btn-reStart" @click="startMyGame">新开一场</div>
            </div>
            <div v-if="identity==0||roomStatus==1" class="f-txt">共5回合,每题10秒回答时间</div>
          </div>
        </div>
      </div>

    </div>
    <!-- 答题页 暂时铺满，根据设计选择模块化-->
    <div class="page-ans" v-if="showQuestion">
      <ans-modules :allData="allData" :answerResponse="resDataList" :roomUserId="user.basicInfo.userId" :withUserId="withUser.basicInfo.userId" :identity="identity" @answerEvent="answerEventHandle" @nextQues="nextQuesHandle" @end="gameOver" @startAgain="startAgain" @startMyGame="startMyGame">
      </ans-modules>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import ansModules from "./components/ansModules";
import userHead from "@/components/public/userHead.vue";

export default {
  onShareAppMessage: function(res) {
    console.log("邀请id：", this.roomId);
    return {
      title: "有种来战",
      path: `pages/entry/index?roomId=${this.roomId}`
    };
  },
  components: {
    "ans-modules": ansModules,
    "user-head": userHead
  },
  data() {
    return {
      showHead:false,
      isFirst: true,
      socketStatus: "off",
      identity: 0, //0,房主 1：选手 2：吃瓜群众  --不同身份 显示不同界面 判断操作依据
      roomType: 1, //0:房间过期，1：房间有效
      roomData: {},
      roomTypeText: "等待开始",
      time: 0,
      timerId: null,
      formateTime: "10:00",
      hasWithUser: false,
      allData: null, //题目数据
      showQuestion: false, //展示答题
      user: { index: 0, restSecond: 0 },
      withUser: { index: 0, restSecond: 0 },
      lookUserList: [],
      resDataList: [], //回调答案列表
      heart:null,
    };
  },
  computed: {
    ...mapState({
      roomId: state => state.fStore.roomId,
      roomStatus: state => state.fStore.roomStatus,
      appInfo: state => state.appInfo
    }),
    userInfo() {
      if (this.user.basicInfo && this.user.basicInfo.nickName) {
        return {
          name: this.user.basicInfo.nickName,
          headImg: this.user.basicInfo.avatarUrl
        };
      } else {
        return { name: "等待房主", headImg: "" };
      }
    },
    withUserInfo() {
      if (this.withUser.basicInfo && this.withUser.basicInfo.nickName) {
        return {
          name: this.withUser.basicInfo.nickName,
          headImg: this.withUser.basicInfo.avatarUrl
        };
      } else {
        return { name: "等待挑战者", headImg: "" };
      }
    }
  },
  watch: {
    time(val) {
      if (val <= 0) {
        this.timeoutHandle();
      } else {
        let m = Math.floor(val / 60) + "";
        let s = val % 60 + "";
        m.length < 2 ? (m = "0" + m) : m;
        s.length < 2 ? (s = "0" + s) : s;
        this.formateTime = `${m}:${s}`;
      }
    },
    user(val) {
      if (!val.basicInfo) {
        //有人逃跑处理
        wx.showToast({
          title: "房主离开，房间失效",
          icon: "none"
        });
        setTimeout(() => {
          this.$router.back();
        }, 1500);
      }
      console.log("user");
    },
    lookUserList(newList, list) {
      const newP = newList.length - list.length;
      let newPeopleList = [];
      let leaveList = [];
      if (newP > 0) {
        //吃瓜群众入场提示
        newPeopleList = newList.slice(list.length, newList.length);
        newPeopleList.forEach(item => {
          if (item.basicInfo.userId == this.appInfo.userId) {
            this.identity = 2;
            console.log("identity=lookUserList=>", "2");
          }
          setTimeout(() => {
            wx.showToast({
              title: `${item.basicInfo.nickName}进来围观`,
              icon: "none",
              duration: 1000
            });
          }, 500);
        });
      } else if (newP < 0) {
        //吃瓜群众退场提示
        list.forEach((item, index) => {
          if (newList.length == 0) {
            leaveList.push(item);
          } else {
            newList.forEach((nItem, index) => {
              if (item.basicInfo.userId != nItem.basicInfo.userId) {
                leaveList.push(item);
              } else {
                leaveList.pop();
              }
            });
          }
        });
        leaveList.forEach(item => {
          setTimeout(() => {
            wx.showToast({
              title: `${item.basicInfo.nickName}离开了`,
              icon: "none",
              duration: 1000
            });
          }, 1000);
        });
      }
    },
    withUser(val) {
      if (val.basicInfo && !this.hasWithUser) {
        //是有有 选手，有的话 提示
        if (val.basicInfo.userId == this.appInfo.userId) {
          //自己是选手
          this.identity = 1;
          console.log("identity=withUser=>", "1");
        }
        this.hasWithUser = true;
        wx.showToast({
          title: `${this.roomData.withUser.basicInfo.nickName}进入房间`,
          icon: "none"
        });
      } else if (!val.basicInfo) {
        this.hasWithUser = false;
      }
    },
    identity(val) {
      console.log("identity:", val);
    }
  },

  methods: {
    ...mapMutations({
      setRoomStatus: "fStore/setRoomStatus",
      setRoomId: "fStore/setRoomId"
    }),
    initSocket() {
      //  初始化socket 建立连接
      // const url = `ws://192.168.2.238:8008/vientianetest/wsRoom?code=${ this.roomId}&userId=${this.appInfo.userId}`;
      const url = `wss://ggbsq.xingpanwang.com/vientianetest/wsRoom?code=${ this.roomId}&userId=${this.appInfo.userId}`;
      console.log(url);
      wx.connectSocket({
        url: url,
        header: {
          "content-type": "application/json"
        },
        method: "GET"
      });
      this.onSocketOpen();
      this.onSocketError();
    },
    onSocketOpen() {
      //监听socket 连接 成功
      wx.onSocketOpen(res => {
        console.log("WebSocket连接打开");
        this.socketStatus = "on";
        this.onSocketMessage(); //监听后端数据事件
        this.onSocketClose();
        this.startHeart();
      });
    },
    onSocketClose() {
      wx.onSocketClose(res => {
        this.resDataList = [];
        this.socketStatus = "off";
        console.log("连接已断开");
        this.stopHeart();
      });
    },
    onSocketError() {
      //监听socket 连接 失败
      wx.onSocketError(res => {
        console.log("WebSocket连接打开失败，请检查！");
      });
    },

    sendSocketMessage(msg, from) {
      //发送消息
      return new Promise((resolve, reject) => {
        wx.sendSocketMessage({
          data: msg,
          success: res => {
            resolve();
          },
          fail: res => {
            console.log("发送失败" + from);
          }
        });
      });
    },

    onSocketMessage() {
      //被动接受消息
      wx.onSocketMessage(res => {
        //区分数据类型 处理不同业务
        let data = JSON.parse(res.data);
        let eventHandleMap = {
          socketType1: () => this.initRoomData(data), //type1 初始化、重置房间信息
          socketType3: () => this.gameStart(data), //type3 游戏开始
          socketType4: () => this.answerResponse(data), //type4 答题信息
          socketType5: () => this.someBodyRun(data), //type5 逃跑
          socketType6: () => null //type5 逃跑
        };
        //执行对应的方法
        if (typeof eventHandleMap[`socketType${data.Type}`] == "function") {
          eventHandleMap[`socketType${data.Type}`]();
        }
      });
    },

    closeSocket() {
      wx.closeSocket();
    },
    startHeart(){
      this.heart=setInterval(()=>{
        this.sendSocketMessage("{'type':0,'data':1}");
      },10000)
    },
    stopHeart(){
      clearInterval(this.heart);
    },
    // socket 处理函数
    initRoomData(data) {
      this.allData = data;
      if (data.Result.game.subjectList) {
        this.showQuestion = true;
        setTimeout(() => {
          this.sendSocketMessage("{'type':3,'data':1}");
        }, 3000);
      }
      this.roomData = data.Result;
      this.user = this.roomData.user;
      this.withUser = this.roomData.withUser;
      this.lookUserList = this.roomData.lookUserList;
      this.roomTypeText = "等待开始";
      this.setRoomStatus(0);
      this.time = this.roomData.restSecond;
      clearInterval(this.timerId);
      this.timerId = setInterval(() => {
        this.time--;
      }, 1000);
      console.log("type1:", data);
    },
    answerEventHandle(obj) {
      //提交答案
      obj.data.gameId = this.roomId;
      obj = JSON.stringify(obj);
      this.sendSocketMessage(obj, "提交答案");
    },
    answerResponse(data) {
      //提交答案回调
      this.resDataList.push(data.Result);
    },
    nextQuesHandle() {
      this.resDataList = [];
      this.sendSocketMessage(
        `{'type':6,'data':'${this.roomId}'}`,
        "send-nextQuestion"
      );
    },
    gameOver() {
      this.sendSocketMessage(
        `{'type':6,'data':'${this.roomId}'}`,
        "send-nextQuestion"
      );
    },
    someBodyRun(data) {
      wx.showToast({
        title:"玩家逃跑,请重新开始对局",
        icon:"none",
        duration:2000
      })
      setTimeout(() => {
        this.$router.back();
      }, 2000);
    },
    cToLook() {
      //成为吃瓜群众
      this.sendSocketMessage("{'type':8,'data':2}"); //1参赛 2围观
    },
    cToJoin() {
      //成为选手
      this.sendSocketMessage("{'type':8,'data':1}"); //1参赛 2围观
    },
    gameStart(data) {
      console.log("type3开始游戏", data);
    },
    startGame() {
      if (this.hasWithUser) {
        this.sendSocketMessage("{'type':1,'data':1}");
      } else {
        wx.showToast({
          title: "请先邀请好友哦",
          icon: "none"
        });
      }
    },
    startNewGame() {
      this.sendSocketMessage("{'type':5,'data':1}").then(() => {
        this.closeSocket();
        wx.showLoading({
          title: "等一下嘛~",
          mask: "true"
        });
        setTimeout(() => {
          wx.hideLoading();
          this.apiClickRoom().then(res => {
            if (res == 0) {
              this.initSocket();
            } else {
              wx.showToast({
                title: "房间已失效",
                icon: "none",
                duration: 1000
              });
              setTimeout(() => {
                this.$router.back();
              }, 1000);
            }
          });
        }, 2000);
      });
    },
    async startMyGame() {
      //房主？重置时间和状态：更换房间id 重置房间数据
      this.showQuestion = false;
      if (this.identity == 0) {
        this.startNewGame();
      } else {
        wx.getStorage({
          //获取自己的房间id
          key: "roomId",
          success: res => {
            this.setRoomId({
              roomId: res.data,
              from: "update"
            });
            this.identity = 0;
            this.startNewGame();
          }
        });
      }
    },
    startAgain() {
      this.resDataList = [];
      this.showQuestion = false;
      this.startNewGame();
    },
    apiClickRoom() {
      return new Promise((resolve, reject) => {
        this.fly.post("/room/clickRoom", { code: this.roomId }).then(res => {
          resolve(res.data.Result.isExpire);
        });
      });
    },
    timeoutHandle() {
      //超时 ，房间失效
      console.log("超时，房间失效，需要重新激活");
      this.formateTime = "00:00";
      this.roomTypeText = "房间失效";
      this.setRoomStatus(1);
      clearInterval(this.timerId);
    },
    leaveRoom() {
      this.$router.back();
    },
    getIdentity() {
      //角色判断
      console.log("getIdentity");
      return new Promise((resolve, reject) => {
        wx.getStorage({
          key: "roomId",
          success: res => {
            if ((res.data == this.roomId)) {
              this.identity = 0;
            } else {
              this.identity = 2;
            }
            resolve();
          },
          fail: res => {
            reject();
          }
        });
      });
    }
  },
  async onShow() {
    //需要判断来源，限制执行。。分享成功后会重新初始化socket
    setTimeout(() => {
      this.showHead=true;
    }, 100);
    if (this.isFirst) {
      let checkIdentity = await this.getIdentity();
      this.isFirst = false;
    }
    if (this.socketStatus == "off") {
      this.initSocket();
    }
  },
  onHide() {
    console.log("hide===========");
  },
  onLoad() {},
  onUnload() {
    this.sendSocketMessage("{'type':5,'data':1}"); // 告诉S端，关闭房间
    this.closeSocket();
    this.showQuestion = false;
    let roomId = wx.getStorageSync("roomId");
    this.setRoomId({
      roomId: roomId,
      from: "updateStore"
    }); //更新roomId 为受邀房间
    this.isFirst = true;
    this.showHead=false;
    this.hasWithUser = false;
  }
};
</script>

<style lang="scss" scoped>
.room {
  height: 100%;
  overflow: hidden;
  background: #fff;
  background-size: 750rpx 714rpx;
  background-position: bottom;
  background-repeat: no-repeat;
  background-image: url("");
}

// 页面通用样式
button {
  border: 2px solid #000;
  border-radius: 10rpx;
  margin: 0;
  padding: 0;
  text-align: center;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

//局部样式
.room {
  font-size: 28rpx;
  color: #000;
}

.head {
  margin-bottom: 200rpx;
  padding-top: 30rpx;
  box-sizing: border-box;
  justify-content: space-between;
  .h-l,
  .h-r {
    display: flex;
    flex-direction: column;
  }
  .h-l-tag,
  .h-r-tag {
    margin-bottom: 10rpx;
    font-size: 40rpx;
    font-weight: bold;
  }
  .h-l-tag {
    text-align: right;
    padding-right: 15rpx;
  }
  .h-r-tag {
    text-align: left;
    padding-left: 15rpx;
  }
  .h-c {
    flex-direction: column;
    align-self: flex-end;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top:190rpx;
    img {
      width: 54rpx;
      height: 54rpx;
    }

    .h-c-time {
      color: #67c29f;
      position: absolute;
      bottom: -60rpx;
      font-size: 40rpx;
    }
  }
}

.content {
  height: 650rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  .c-type {
    align-items: flex-start;
    text-align: center;
    color: #aaaaaa;
    font-size: 40rpx;
    font-weight: bold;
  }
  .c-btn {
    button {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 186rpx;
      height: 186rpx;
      border-radius: 50%;
      margin-right: 54rpx;
      border: 4rpx solid #d6d6d6;
      box-sizing: border-box;
      font-size: 36rpx;
      color: #d6d6d6;
      &:last-child {
        margin-right: 0;
      }
      &>div{
        line-height: 2em;
      }
    }
    .btnActive{
      border-color: #67c29f;
      color: #67c29f;
    }
    .btn-leave{
      img{
        width: 59rpx;
        height: 64rpx;
      }
    }
    .btn-join,.btn-invate{
      img{
        width: 76rpx;
        height: 64rpx;
      }
    }
    .btn-watch{
      img{
        width: 90rpx;
        height: 64rpx;
      }
    }
  }

  .c-look-num {
    margin: 30rpx 0;
    text-align: center;
    font-size: 30rpx;
    color: #67c29f;
  }
}

.foot {
  .f-btn {
    > div {
      margin: 0 auto;
      width: 392rpx;
      height: 120rpx;
      line-height: 120rpx;
      text-align: center;
      margin-bottom: 20rpx;
      background: #67c29f;
      border-radius: 1000rpx;
      color: #fff;
      font-size: 44rpx;
    }
  }
  .f-txt {
    font-size: 28rpx;
    color: #aaa;
    text-align: center;
  }
}
</style>
